package com.bawei.module_park.ui

import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.GridLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.lib_common.Router
import com.bawei.lib_common.base.BaseViewModel
import com.bawei.lib_common.base.utils.ToastUtils
import com.bawei.module_park.R
import com.bawei.module_park.adapter.ParkHomeMultiAdapter
import com.bawei.module_park.databinding.FragmentParkBinding
import com.bawei.module_park.model.ContentItem
import com.bawei.myclub.base.mvvm.view.BaseFragment
import com.google.android.material.dialog.MaterialAlertDialogBuilder


@Route(path = Router.Ui.ParkFragment)
class ParkFragment : BaseFragment<BaseViewModel, FragmentParkBinding>() {
    override val mLayoutResId: Int
        get() = R.layout.fragment_park

    override val mViewModel: BaseViewModel by viewModels()

    private lateinit var mAdapter: ParkHomeMultiAdapter
    private val dataSource = mutableListOf<ContentItem>()

    override fun initView() {
        super.initView()
        setupRecyclerView()
        initData()
    }

    override fun initData() {
        // 创建新数据集（在实际应用中可能来自网络或数据库）
        val newItems = generateContentItems()

        // 更新数据源
        dataSource.clear()
        dataSource.addAll(newItems)
        mAdapter.notifyItemRangeChanged(0, newItems.size)
    }

    override fun initListener() {
        super.initListener()

    }


    private fun setupRecyclerView() {
        val layoutManager = GridLayoutManager(requireActivity(), 4).apply {
            spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
                override fun getSpanSize(position: Int): Int {
                    return when (dataSource.getOrNull(position)) {
                        is ContentItem.FunctionItem -> 1 // 每行4个功能图标
                        else -> 4 // 其他条目占一整行
                    }
                }
            }
        }

        mBinding.rvPark.layoutManager = layoutManager

        // 创建适配器并设置回调
        mAdapter = ParkHomeMultiAdapter(dataSource) { item ->
            when (item) {
                is ContentItem.FunctionItem -> {
                    // 处理功能图标点击事件->跳转对应页面
                    when (item.iconType) {
                        "车位管理" -> {
                            ARouter.getInstance().build(Router.Ui.CarSpaceActivity).navigation()
                        }

                        "访客登记" -> {
                            ARouter.getInstance().build(Router.Ui.VisitorAddActivity).navigation()
                        }

                        "物业报修" -> {
                            ARouter.getInstance().build(Router.Ui.DemoActivity).navigation()
                        }

                        "考勤打卡" -> {
                            ARouter.getInstance().build(Router.Ui.ClockActivity).navigation()
                        }

                        "房源信息" -> {
                            ARouter.getInstance().build(Router.Ui.HomeActivity).navigation()
                        }

                        "商家推荐" -> {
                            ARouter.getInstance().build(Router.Ui.RecommendActivity).navigation()
                        }

                        "月卡会员" -> {
                            ARouter.getInstance().build(Router.Ui.VipActivity).navigation()
                        }

                        "设备管理" -> {
                           ARouter.getInstance().build(Router.Ui.EquipmentActivity).navigation()
                        }
                    }
                }

            }
        }

        mBinding.rvPark.adapter = mAdapter

    }


    private fun generateContentItems(): List<ContentItem> {
        return listOf(

            // 搜索框（对应图3）
            ContentItem.SearchBarItem(R.layout.item_search),

            // 建筑景观图（对应图2）
            ContentItem.AdItem(R.layout.item_ad_banner),

            ContentItem.FunctionItem(R.mipmap.img1, "车位管理"),
            ContentItem.FunctionItem(R.mipmap.img2, "访客登记"),
            ContentItem.FunctionItem(R.mipmap.img3, "物业报修"),
            ContentItem.FunctionItem(R.mipmap.img4, "考勤打卡"),
            ContentItem.FunctionItem(R.mipmap.img5, "房源信息"),
            ContentItem.FunctionItem(R.mipmap.img6, "商家推荐"),
            ContentItem.FunctionItem(R.mipmap.img7, "月卡会员"),
            ContentItem.FunctionItem(R.mipmap.img8, "设备管理"),

            ContentItem.RowTitle("园区公告"),

            // 公告列表（对应图4）
            ContentItem.NoticeItem(
                title = "园区消防演习通知",
                content = "定于本周五上午10:00进行年度消防演习，请各位租户配合参与。",
                date = "2023-10-20"
            ),
            ContentItem.NoticeItem(
                title = "停车场维护公告",
                content = "1号楼地下停车场将于10月25日进行维护保养，请提前安排停车位置。",
                date = "2023-10-18"
            ),
            ContentItem.NoticeItem(
                title = "租金缴纳提醒",
                content = "本月租金请于10月30日前缴纳，逾期将产生滞纳金。",
                date = "2023-10-15"
            )
        )
    }

    // 添加新的数据（示例）
    private fun addNewNotice() {
        val newNotice = ContentItem.NoticeItem(
            title = "新增通知：节日祝福",
            content = "祝全体居民国庆节快乐！节日期间请加强安全意识。",
            date = "2023-10-01"
        )

        // 找到公告开始的位置（在搜索框之后）
        val noticeIndex = dataSource.indexOfFirst { it is ContentItem.NoticeItem }

        if (noticeIndex == -1) {
            // 如果还没有公告，在搜索框后添加
            val searchIndex = dataSource.indexOfFirst { it is ContentItem.SearchBarItem }
            if (searchIndex != -1) {
                dataSource.add(searchIndex + 1, newNotice)
                mAdapter.notifyItemInserted(searchIndex + 1)
            } else {
                // 如果还没有搜索框，在最后添加
                dataSource.add(newNotice)
                mAdapter.notifyItemInserted(dataSource.size - 1)
            }
        } else {
            // 在现有公告中插入为新公告（放在第一个）
            dataSource.add(noticeIndex, newNotice)
            mAdapter.notifyItemInserted(noticeIndex)
        }

        // 滚动到新公告位置
        mBinding.rvPark.scrollToPosition(dataSource.indexOf(newNotice))
    }

    // 更新单个功能图标数据
    private fun updateFunctionItemProgress(itemName: String, newProgress: Int) {
        val position = dataSource.indexOfFirst {
            it is ContentItem.FunctionItem && it.iconType == itemName
        }

        if (position != -1) {
            val item = dataSource[position] as ContentItem.FunctionItem
            dataSource[position] = updateItem(item)
            mAdapter.notifyItemChanged(position)
        }
    }

    fun updateItem(newItem: ContentItem): ContentItem {
        val position = dataSource.indexOfFirst { newItem == it }
        if (position != -1) {
            dataSource[position] = newItem
            mAdapter.notifyItemChanged(position)
        }
        return newItem
    }

    // 处理功能图标点击
    private fun handleFunctionItemClick(item: ContentItem.FunctionItem) {

        // 根据功能类型执行不同操作
        when (item.iconType) {

        }
    }

    // 处理搜索功能
    private fun performSearch(query: String) {
        if (query.isNotBlank()) {
            // 实际搜索逻辑
            ToastUtils.showLong(requireActivity(), "搜索: $query")

            // 示例：过滤显示相关内容
            val filteredItems = dataSource.filter {
                when (it) {
                    is ContentItem.NoticeItem -> it.title.contains(query, true) ||
                            it.content.contains(query, true)

                    is ContentItem.FunctionItem -> it.iconType.contains(query, true)
                    else -> false
                }
            }

            // 显示搜索结果
            dataSource.clear()
            dataSource.addAll(filteredItems)
            mAdapter.notifyDataSetChanged()
        }
    }


    // 显示公告详情
    private fun showNoticeDetails(noticeItem: ContentItem.NoticeItem) {
        val dialog = MaterialAlertDialogBuilder(requireContext())
            .setTitle(noticeItem.title)
            .setMessage("${noticeItem.content}\n\n发布日期: ${noticeItem.date}")
            .setPositiveButton("确定") { dialog, _ -> dialog.dismiss() }
            .show()
    }

    // 工具方法：dp转px
    private fun dpToPx(dp: Int): Int {
        return (dp * resources.displayMetrics.density).toInt()
    }
}


